const crypto = require('crypto')
const contentType = require('content-type')
const getRawBody = require('raw-body')
const convert = require('xml-js')

const auth = (ctx) => {
  const { signature, nonce, echostr, timestamp } = ctx.request.query
  const token = 'weixin'

  const sortedStr = [token, timestamp, nonce].sort().join('')
  const sign = crypto.createHash('sha1').update(sortedStr).digest('hex')
  
  if (signature === sign) {
    ctx.body = echostr
  } else {
    ctx.body = 'error'
  }
}

const reply = async (ctx) => {
  const xml = (await getRawBody(ctx.req, {
    length: ctx.req.headers['content-length'],
    limit: '1mb',
    encoding: contentType.parse(ctx.req).parameters.charset
  })).toString()

  const js = convert.xml2js(xml, {
    compact: true,
    textKey: 'value',
    cdataKey: 'value'
  }).xml

  const {
    ToUserName,
    FromUserName
  } = Object.keys(js).reduce((obj, key) => {
    obj[key] = js[key]['value']
    return obj
  }, {})

  await ctx.render('reply', {
    toUser: FromUserName,
    fromUser: ToUserName,
    createTime: new Date().getTime(),
    // content: '<a href="https://walter666.cn">cookbook</a>'
    content: '<a href="https://walter666.cn/jssdk.html">扫码</a>'
  })
}

module.exports = {
  auth,
  reply
}